package ui;

import ga.Path;
import ga.Point;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.util.List;

import javax.swing.JComponent;

import utilities.JEasyFrame;

public class MapView extends JComponent {

	private static final long serialVersionUID = 1L;
	
	private Path fittest = null;
	
    private int rad = 5;
    private final static int space = 20;
    private final static Color background = Color.white;
    private final static Color pointColor = Color.blue;
    private final static Color idealColor = Color.black;
    int n = 0;

    public MapView() {
        setFocusable(true);
        new JEasyFrame(this, "Map View", true);
    }

    public void paintComponent(Graphics g) {
        g.setColor(background);
        g.fillRect(0, 0, Map.WIDTH, Map.HEIGHT);
        drawGrid(g);
        if (fittest != null){
        	drawIdealPath(g);
        	g.setFont(new Font("Arial", Font.BOLD, 14));
        	g.drawString("Total distance: "+fittest.getDistance(), Map.WIDTH-200, Map.HEIGHT-10);
        }
    }

	private void drawGrid(Graphics g) {
		g.setColor(Color.lightGray);
        for(int i = 0; i<Map.HEIGHT/space; i++){
        	g.drawLine(0, i*space, Map.WIDTH, i*space);
        }
        for(int i = 0; i<Map.WIDTH/space; i++){
        	g.drawLine(i*space, 0, i*space,Map.HEIGHT);
        }
        for (Point p : fittest.getPath()) {
        	g.setColor(pointColor);
            g.fillOval(p.getX() - rad, p.getY() - rad, rad * 2, rad * 2);
        }
	}

	private void drawIdealPath(Graphics g) {
		g.setColor(idealColor);
		List<Point> path = fittest.getPath();
		for (int i = 0; i < path.size(); i++) {
			Point p1 = path.get(i);
			Point p2 = null;
			if(i+1>=path.size()){
				p2 = path.get(0);
			}else {
				p2 = path.get(i+1);
			}
			g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY());
		}
	}
    
    public Dimension getPreferredSize() {
        return new Dimension(Map.WIDTH, Map.HEIGHT);
    }

	public void setFittest(Path fittest) {
		this.fittest = fittest;
	}


}
